package com.example.sunmiv1.adapter;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.NewInventoryActivity;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class InventoryListAdapter extends RecyclerView.Adapter<InventoryListAdapter.ViewHolder> {
    // 填充數據的list
    private List<ReportLossGoodBean.DataBean.ListBean> list;
    // 上下文
    private Context context;
    private ACache aCache;
    private Resources resources;
    private Choose choose;
    // 用來導入佈局
    private LayoutInflater inflater;
    private onTextChangeListener mTextListener;
    private static final String TAG = "InventoryListAdapter";

    // 構造器
    public InventoryListAdapter(Context context, List<ReportLossGoodBean.DataBean.ListBean> list) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
        aCache = ACache.get(context);
        resources = context.getResources();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.inventory_search_adapter, parent, false);
        return new ViewHolder(view);
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        if (select == position) {
            holder.inventorySearchAdapterView.setBackgroundResource(R.drawable.red_border);
        } else {
            holder.inventorySearchAdapterView.setBackgroundResource(R.color.white);
        }
        holder.inventorySearchAdapterName.setText(resources.getString(R.string.inventory_name) + list.get(position).getGoods_name());
        if ("2".equals(list.get(position).getAttribute_state())) {
            holder.inventorySearchAdapterSku.setText(resources.getString(R.string.inventory_sku) +
                    list.get(position).getSku_name());
            holder.inventorySearchAdapterFreightNumber.setText(resources.getString(R.string.inventory_freightNumber) + list.get(position).getSku_goods_number());
            holder.inventorySearchAdapterBarcode.setText(resources.getString(R.string.inventory_barcode) + list.get(position).getSku_code());
        } else {
            holder.inventorySearchAdapterSku.setVisibility(View.GONE);
            holder.inventorySearchAdapterBarcode.setText(resources.getString(R.string.inventory_barcode) + list.get(position).getGoods_code());
            holder.inventorySearchAdapterFreightNumber.setText(resources.getString(R.string.inventory_freightNumber) + list.get(position).getGoods_number());
        }
        holder.inventorySearchAdapterStock.setText(list.get(position).getGoods_num() + "");
        holder.inventorySearchAdapterInventory.setText(list.get(position).getInventory_num());
        holder.inventorySearchAdapterInventoryTv.setText(list.get(position).getInventory_num());
        if ("1".equals(list.get(position).getSerial_number_state())) {
            holder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            holder.inventorySearchAdapterInventory.setVisibility(View.GONE);
            holder.inventorySearchAdapterStock.setTextColor(ContextCompat.getColor(context,R.color.login_textColor1));
            Log.e(TAG, "onBindViewHolder: 商品的庫存========" + list.get(position).getInventory_num());
            if (TextUtils.isEmpty(list.get(position).getInventory_num())) {
                holder.inventorySearchAdapterInventoryTv.setText("0");
            } else {
                holder.inventorySearchAdapterInventoryTv.setText(list.get(position).getInventory_num());
            }
        } else {
            holder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            holder.inventorySearchAdapterInventory.setVisibility(View.VISIBLE);
            holder.inventorySearchAdapterStock.setTextColor(ContextCompat.getColor(context,R.color.text_666));
        }
        if (TextUtils.isEmpty(list.get(position).getCompany())) {
            holder.inventorySearchAdapterUnit.setVisibility(View.GONE);
        } else {
            holder.inventorySearchAdapterUnit.setVisibility(View.VISIBLE);
            holder.inventorySearchAdapterUnit.setText(resources.getString(R.string.purRefundDetail_company) + ":" +
                    list.get(position).getCompany());
        }
        if (NewInventoryActivity.opera) {
            holder.inventorySearchAdapterCheck.setVisibility(View.VISIBLE);
        } else {
            holder.inventorySearchAdapterCheck.setVisibility(View.GONE);
        }
        holder.inventorySearchAdapterCheck.setOnCheckedChangeListener(null);
        holder.inventorySearchAdapterCheck.setChecked(list.get(position).isChecked());
        holder.inventorySearchAdapterCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            list.get(position).setChecked(isChecked);
            notifyDataSetChanged();
        });
        final EditText inventory = holder.inventorySearchAdapterInventory;
        final int index = position;
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                LogUtil.i(TAG + "onTextChanged: charSequence=" + charSequence.toString());
                if (charSequence.toString().contains(".")) {
                    if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                        inventory.setText(charSequence.toString().
                                substring(0, charSequence.toString().length() - 1));
                        inventory.setSelection(charSequence.length() - 1);
                    } else {
                        if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                            charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                            inventory.setText(charSequence);
                            inventory.setSelection(charSequence.length());
                        }
                    }
                }
                if (charSequence.toString().trim().equals(".")) {
                    charSequence = "0" + charSequence;
                    inventory.setText(charSequence);
                    inventory.setSelection(2);
                }

                if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
                    if (!charSequence.toString().substring(1, 2).equals(".")) {
                        inventory.setText(charSequence.subSequence(1, 2));
                        inventory.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
//                list.get(index).setInventory_num(s.toString().trim());
                mTextListener.onTextChanged(position, inventory.getText().toString().trim());
            }
        };
        inventory.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    holder.inventorySearchAdapterInventory.addTextChangedListener(textWatcher);
                } else {
                    holder.inventorySearchAdapterInventory.removeTextChangedListener(textWatcher);
                }
            }
        });
        if ("2".equals(aCache.getAsString("supplier_type"))) {
            holder.llPurchaseOrderChoose.setVisibility(View.VISIBLE);
            final List<ReportLossGoodBean.DataBean.ListBean.PurData> spinnerList = new ArrayList<>();
            spinnerList.add(new ReportLossGoodBean.DataBean.ListBean.PurData("", "未選"));
            spinnerList.addAll(list.get(position).getPur_id());
            final ArrayAdapter<ReportLossGoodBean.DataBean.ListBean.PurData> adapter = new ArrayAdapter<ReportLossGoodBean.DataBean.ListBean.PurData>(context, android.R.layout.simple_list_item_1, spinnerList) {
                @Override
                public View getDropDownView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                    @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(android.R.layout.simple_list_item_single_choice, parent, false);
                    final TextView text = view.findViewById(android.R.id.text1);
                    text.setText(spinnerList.get(pos).getOrder_number());
                    text.setTextSize(14);
                    return view;
                }

                @NonNull
                @Override
                public View getView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                    @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
                    final TextView text = view.findViewById(android.R.id.text1);
                    text.setText(spinnerList.get(pos).getOrder_number());
                    text.setTextSize(14);
                    return view;
                }
            };
            final Spinner spinner = holder.spinnerPurchaseOrder;
            spinner.setAdapter(adapter);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    list.get(position).setPurchase_order_id(spinnerList.get(pos).getPurchase_order_id());
                    LogUtil.e("holder.spinnerPurchaseOrder.onItemSelected():" + list.get(position).getPurchase_order_id());
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            for (ReportLossGoodBean.DataBean.ListBean.PurData data : list.get(position).getPur_id()) {
                if (!TextUtils.isEmpty(list.get(position).getPurchase_order_id()) && data.getPurchase_order_id().equals(list.get(position).getPurchase_order_id())) {
                    spinner.setSelection(list.get(position).getPur_id().indexOf(data), true);
                }
            }
        } else {
            holder.llPurchaseOrderChoose.setVisibility(View.GONE);
        }
        holder.inventorySearchAdapterStock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(index, 1);
            }
        });
        holder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(index, 2);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    private int select = 9999;

    public void setSelect(int select) {
        this.select = select;
        notifyDataSetChanged();
    }

    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index, int type);
    }


    //設置Edit監聽
    public void setOnTextChangeListener(onTextChangeListener onTextChangeListener) {
        this.mTextListener = onTextChangeListener;
    }

    public interface onTextChangeListener {
        void onTextChanged(int pos, String str);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.inventorySearch_adapter_view)
        LinearLayout inventorySearchAdapterView;
        @BindView(R.id.inventorySearch_adapter_check)
        CheckBox inventorySearchAdapterCheck;
        @BindView(R.id.inventorySearch_adapter_name)
        TextView inventorySearchAdapterName;
        @BindView(R.id.inventorySearch_adapter_sku)
        TextView inventorySearchAdapterSku;
        @BindView(R.id.inventorySearch_adapter_freightNumber)
        TextView inventorySearchAdapterFreightNumber;
        @BindView(R.id.inventorySearch_adapter_barcode)
        TextView inventorySearchAdapterBarcode;
        @BindView(R.id.inventorySearch_adapter_stock)
        TextView inventorySearchAdapterStock;
        @BindView(R.id.inventorySearch_adapter_inventory)
        EditText inventorySearchAdapterInventory;
        @BindView(R.id.spinner_purchase_order)
        Spinner spinnerPurchaseOrder;
        @BindView(R.id.ll_purchase_order_choose)
        LinearLayout llPurchaseOrderChoose;
        @BindView(R.id.inventorySearch_adapter_unit)
        TextView inventorySearchAdapterUnit;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

}
